package com.xgk.boot.module.core.logistics.service.mothership;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.xgk.boot.framework.common.constant.ErrorCodeConstants;
import com.xgk.boot.framework.common.exception.util.ServiceExceptionUtil;
import com.xgk.boot.framework.common.util.object.BeanUtils;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrdersDO;
import com.xgk.boot.module.core.logistics.service.dto.RespOrderDto;
import com.xgk.boot.module.core.logistics.service.dto.RespRateDto;
import com.xgk.boot.module.core.logistics.service.mothership.dto.*;
import com.xgk.boot.module.core.logistics.service.mothership.response.*;
import com.xgk.boot.module.core.util.HighHttpUtil;
import com.xgk.boot.framework.common.util.json.JsonUtils;
import com.xgk.boot.module.core.dal.dto.TruckOrderDto;
import com.xgk.boot.module.core.dal.entity.channel.ApiServiceDO;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrderAddressDO;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrderBoxDO;
import com.xgk.boot.module.core.logistics.common.LogisticsCache;
import com.xgk.boot.module.core.logistics.inter.ShippingService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class MotherShipperServiceImpl implements ShippingService {

    /**
     * 实现类编码，这个code是和物流服务商的code保持一致的
     * 一个物流服务商可能存在多个api类（对应的token、 ak/sk/ url等可能不同）
     */
    private static final String SHIPPING_CODE = "mothership";
    private static final String SHIPPING_NAME = "mothership物流";
    private static final Map<String,String> SHIPPING_URL_MAP = new HashMap<>();

    static {
        SHIPPING_URL_MAP.put("getOrderQuotation","/beta/quotes");
        SHIPPING_URL_MAP.put("createOrder","/beta/shipments");
        SHIPPING_URL_MAP.put("listShipment","/beta/shipments");
        SHIPPING_URL_MAP.put("getOrderDetail","/beta/shipments/");
        SHIPPING_URL_MAP.put("getOrderStatus","/beta/shipments/");
        SHIPPING_URL_MAP.put("getOrderTracking","/beta/tracking/");
        SHIPPING_URL_MAP.put("getOrderBol","/beta/documents/");
    }




    public MotherShipperServiceImpl() {
        // 可以在这里进行一些初始化操作
        log.info("Initializing ShipperService with code: {}", SHIPPING_CODE);
        LogisticsCache.SHIPPING_CODE_MAP.put(SHIPPING_CODE, this);
    }


    @Override
    public String getShippingName() {
        return SHIPPING_NAME;
    }

    @Override
    public String getShippingCode() {
        return SHIPPING_CODE;
    }


    @Override
    public Object checkOrderAddress(TruckOrderDto orderInfo) {
        log.error("checkOrderAddress not implemented for {}. Please implement this method in the shipping service.", SHIPPING_CODE);
        throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "checkOrderAddress");
    }

    @Override
    public Object validateOrderAddress(TruckOrderDto orderInfo) {
        log.error("validateOrderAddress not implemented for {}. Please implement this method in the shipping service.", SHIPPING_CODE);
        throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "validateOrderAddress");
    }

    /**
     * 获取订单报价列表
     * @param orderInfo
     * @return
     */
    @Override
    public RespRateDto getOrderQuotation(TruckOrderDto orderInfo) throws IOException {
        //1、构建物流订单信息
        OrderCreateDto orderCreateDto = factoryOrder(orderInfo);
        String body = JsonUtils.toJsonString(orderCreateDto);
        log.info("getOrderQuotation request body: {}", body);
        String getOrderQuotation = SHIPPING_URL_MAP.get("getOrderQuotation");
        if(StrUtil.isBlank(getOrderQuotation)) {
            log.error("getOrderQuotation url not found for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "getOrderQuotation");
        }
        ApiServiceDO apiServiceDO = orderInfo.getApiServiceDO();
        if(apiServiceDO == null) {
            log.error("ApiServiceDO is null for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO");
        }
        String domain = apiServiceDO.getAsAddress();
        if(StrUtil.isBlank(domain)) {
            log.error("ApiServiceDO address is blank for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO address");
        }
        String url = domain + getOrderQuotation;
        Map<String, String> header = HighHttpUtil.addAuthBearerHeader(null, apiServiceDO.getAsToken());
        //2、构建请求结构体
        Response res= HighHttpUtil.postJson(url, body, header);
        if (res.code() == 201){
            //请求成功
            String repData = res.body().string();
            RespDataDto respDataDto = JsonUtils.parseObject(repData, RespDataDto.class);
            QuotationDto quotationDto = BeanUtils.toBean(respDataDto.getData(), QuotationDto.class);
            quotationDto.getRates().forEach(rateDto -> {
                rateDto.setQuoteId(quotationDto.getId());
            });
            RespRateDto respRateDto = new RespRateDto().setRates(quotationDto.getRates());
            respRateDto.setResponseId(quotationDto.getId());
            if(quotationDto.getMetadata() !=null){
                List<InvalidFieldsRequiredDto> invalidFieldsRequiredForPurchase = quotationDto.getMetadata().getInvalidFieldsRequiredForPurchase();
                invalidFieldsRequiredForPurchase.forEach(e->e.setRequired(true));
                respRateDto.setWarnings(invalidFieldsRequiredForPurchase);
            }
            return respRateDto.setCode("200");
        }
            //请求异常，处理异常结果
            ErrorDto respErrorDto = JsonUtils.parseObject(res.body().string(), ErrorDto.class);
        return new RespRateDto().setCode(String.valueOf(res.code()))
                .setErrorMessage("errorType:"+respErrorDto.getType()+",msg:"+respErrorDto.getMessage());

    }


//    public static void main(String[] args) {
//        String aa ="{\"data\":{\"id\":\"fake-success-quote-key\",\"expiresAt\":\"2025-07-21T15:00:05.811Z\",\"rates\":[{\"id\":\"12345\",\"coveragePrice\":0,\"coveredValue\":0,\"creditsApplied\":0,\"estimatedPickupDate\":\"2025-07-21T15:00:05.811Z\",\"estimatedDeliveryDate\":\"2025-07-21T15:00:05.811Z\",\"price\":142.3,\"provider\":\"mothership\",\"providerScac\":\"mhpg\",\"services\":[],\"serviceType\":\"nextDay\",\"transitDays\":{\"minimum\":1,\"maximum\":1},\"truck\":{\"equipment\":\"straightTruck\",\"specialty\":\"dryVan\"},\"warnings\":[]}],\"freight\":[{\"quantity\":1,\"type\":\"Pallet\",\"weight\":100,\"length\":100,\"width\":100,\"height\":100,\"description\":\"Fake Cargo\"}],\"pickup\":{\"placeId\":\"123\",\"name\":\"Pickup Place\",\"street\":\"123rd Pickup St\",\"city\":\"SomeCity\",\"state\":\"SomeState\",\"zip\":\"12345\",\"accessorials\":[],\"phoneNumber\":\"+18888888888\",\"openTime\":\"0800\",\"closeTime\":\"1700\",\"emails\":[]},\"delivery\":{\"placeId\":\"456\",\"name\":\"Delivery Place\",\"street\":\"123rd Delivery St\",\"city\":\"SomeCity\",\"state\":\"SomeState\",\"zip\":\"12345\",\"accessorials\":[],\"phoneNumber\":\"+15555555555\",\"openTime\":\"0800\",\"closeTime\":\"1700\",\"emails\":[]},\"metadata\":{\"purchasable\":true,\"invalidFieldsRequiredForPurchase\":[],\"pickupLocationSuggestedAccessorials\":[],\"deliveryLocationSuggestedAccessorials\":[]}}}";
//        QuotationDto quotationDto = JsonUtils.parseObject(aa, QuotationDto.class);
//        System.out.println(quotationDto.getRates().get(0).getQuoteId());
//    }
    /**
     * 订单预报
     * @param orderInfo
     * @return
     */
    @Override
    public Object preAdviceOrder(TruckOrderDto orderInfo) {
        log.error("validateOrderAddress not implemented for {}. Please implement this method in the shipping service.", SHIPPING_CODE);
        throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "validateOrderAddress");
    }

    /**
     * 创建订单
     *
     * @param orderInfo
     * @return
     */
    @Override
    public RespOrderDto createOrder(TruckOrderDto orderInfo) throws IOException {
        if(orderInfo.getTruckOrderQuotationChoice() == null || orderInfo.getTruckOrderQuotationChoice().getChoiceQuotationDto()==null ) {
            log.error("订单信息中缺少待下单的物流报价信息");
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "truckOrderQuotationChoice");
        }
        String body = JsonUtils.toJsonString(orderInfo.getTruckOrderQuotationChoice().getChoiceQuotationDto());
        String createOrderUrl = SHIPPING_URL_MAP.get("createOrder");
        if(StrUtil.isBlank(createOrderUrl)) {
            log.error("getOrderQuotation url not found for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "getOrderQuotation");
        }
        ApiServiceDO apiServiceDO = orderInfo.getApiServiceDO();
        if(apiServiceDO == null) {
            log.error("ApiServiceDO is null for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO");
        }
        String domain = apiServiceDO.getAsAddress();
        if(StrUtil.isBlank(domain)) {
            log.error("ApiServiceDO address is blank for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO address");
        }
        String url = domain + createOrderUrl;
        Map<String, String> header = HighHttpUtil.addAuthBearerHeader(null, apiServiceDO.getAsToken());
        //2、构建请求结构体
        Response res= HighHttpUtil.postJson(url, body, header);
        if (res.code() == 201){
            //请求成功
            String repData = res.body().string();
            RespDataDto respDataDto = JsonUtils.parseObject(repData, RespDataDto.class);
            OrderDto orderDto = BeanUtils.toBean(respDataDto.getData(), OrderDto.class);
            return new RespOrderDto().setOrderDto(orderDto)
                    .setCode("200");
        }
        //请求异常，处理异常结果
        ErrorDto respErrorDto = JsonUtils.parseObject(res.body().string(), ErrorDto.class);
        return new RespOrderDto().setCode(String.valueOf(res.code()))
                .setErrorMessage("errorType:"+respErrorDto.getType()+",msg:"+respErrorDto.getMessage());
    }

    /**
     * 取消订单
     * @param orderInfo
     * @return
     */
    @Override
    public Object cancelOrder(TruckOrderDto orderInfo) {
        log.error("cancelOrder not implemented for {}. Please implement this method in the shipping service.", SHIPPING_CODE);
        throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "cancelOrder");
    }

    /**
     * 获取订单状态
     * @param orderInfo
     * @return
     */
    @Override
    public Object getOrderStatus(TruckOrderDto orderInfo) {
        return null;
    }

    /**
     * 获取面单信息
     * @param orderInfo
     * @return
     */
    @Override
    public Object getOrderLabel(TruckOrderDto orderInfo) {
        return null;
    }

    @Override
    public RespOrderDto getOrderBol(TruckOrderDto orderInfo) throws IOException {
        String reqUrl = SHIPPING_URL_MAP.get("getOrderBol");
        if(StrUtil.isBlank(reqUrl)) {
            log.error("getOrderQuotation url not found for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "getOrderQuotation");
        }
        ApiServiceDO apiServiceDO = orderInfo.getApiServiceDO();
        if(apiServiceDO == null) {
            log.error("ApiServiceDO is null for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO");
        }
        String domain = apiServiceDO.getAsAddress();
        if(StrUtil.isBlank(domain)) {
            log.error("ApiServiceDO address is blank for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO address");
        }
        TruckOrdersDO truckOrdersDO = orderInfo.getTruckOrdersDO();
        String url = domain + reqUrl+truckOrdersDO.getTrackingNumber();
        Map<String, String> header = HighHttpUtil.addAuthBearerHeader(null, apiServiceDO.getAsToken());
        //2、构建请求结构体
        Response res= HighHttpUtil.get(url,  header);
        if (res.code() == 200){
            //请求成功
            String repData = res.body().string();
            RespBolDataDto respDataDto = JsonUtils.parseObject(repData, RespBolDataDto.class);

            OrderDto orderDto = new OrderDto();
            orderDto.setOrderBols(respDataDto.getData());
            return new RespOrderDto().setOrderDto(orderDto)
                    .setCode("200");
        }
        //请求异常，处理异常结果
        ErrorDto respErrorDto = JsonUtils.parseObject(res.body().string(), ErrorDto.class);
        return new RespOrderDto().setCode(String.valueOf(res.code()))
                .setErrorMessage("errorType:"+respErrorDto.getType()+",msg:"+respErrorDto.getMessage());
    }

    /**
     * 获取订单跟踪信息
     * @param orderInfo
     * @return
     */
    @Override
    public RespOrderDto getOrderTracking(TruckOrderDto orderInfo)  throws IOException{
        String reqUrl = SHIPPING_URL_MAP.get("getOrderTracking");
        if(StrUtil.isBlank(reqUrl)) {
            log.error("getOrderQuotation url not found for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "getOrderQuotation");
        }
        ApiServiceDO apiServiceDO = orderInfo.getApiServiceDO();
        if(apiServiceDO == null) {
            log.error("ApiServiceDO is null for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO");
        }
        String domain = apiServiceDO.getAsAddress();
        if(StrUtil.isBlank(domain)) {
            log.error("ApiServiceDO address is blank for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO address");
        }
        TruckOrdersDO truckOrdersDO = orderInfo.getTruckOrdersDO();
        String url = domain + reqUrl+truckOrdersDO.getTrackingNumber();
        Map<String, String> header = HighHttpUtil.addAuthBearerHeader(null, apiServiceDO.getAsToken());
        //2、构建请求结构体
        Response res= HighHttpUtil.get(url,  header);
        if (res.code() == 200){
            //请求成功
            String repData = res.body().string();
            RespTrackDataDto respDataDto = JsonUtils.parseObject(repData, RespTrackDataDto.class);

            OrderDto orderDto = new OrderDto();
            orderDto.setOrderTracks(respDataDto.getData().getResults());
            return new RespOrderDto().setOrderDto(orderDto)
                    .setCode("200");
        }
        //请求异常，处理异常结果
        ErrorDto respErrorDto = JsonUtils.parseObject(res.body().string(), ErrorDto.class);
        return new RespOrderDto().setCode(String.valueOf(res.code()))
                .setErrorMessage("errorType:"+respErrorDto.getType()+",msg:"+respErrorDto.getMessage());
    }

    /**
     *
     * @param orderInfo
     * @return
     */
    @Override
    public RespOrderDto getOrderDetail(TruckOrderDto orderInfo) throws IOException {

        String createOrderUrl = SHIPPING_URL_MAP.get("getOrderDetail");
        if(StrUtil.isBlank(createOrderUrl)) {
            log.error("getOrderQuotation url not found for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_NOT_SUPPORTED, "getOrderQuotation");
        }
        ApiServiceDO apiServiceDO = orderInfo.getApiServiceDO();
        if(apiServiceDO == null) {
            log.error("ApiServiceDO is null for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO");
        }
        String domain = apiServiceDO.getAsAddress();
        if(StrUtil.isBlank(domain)) {
            log.error("ApiServiceDO address is blank for {}", SHIPPING_CODE);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "apiServiceDO address");
        }
        TruckOrdersDO truckOrdersDO = orderInfo.getTruckOrdersDO();
        String url = domain + createOrderUrl+truckOrdersDO.getTrackingNumber();
        Map<String, String> header = HighHttpUtil.addAuthBearerHeader(null, apiServiceDO.getAsToken());
        //2、构建请求结构体
        Response res= HighHttpUtil.get(url,  header);
        if (res.code() == 200){
            //请求成功
            String repData = res.body().string();
            RespDataDto respDataDto = JsonUtils.parseObject(repData, RespDataDto.class);
            OrderDto orderDto = BeanUtils.toBean(respDataDto.getData(), OrderDto.class);
            return new RespOrderDto().setOrderDto(orderDto)
                    .setCode("200");
        }
        //请求异常，处理异常结果
        ErrorDto respErrorDto = JsonUtils.parseObject(res.body().string(), ErrorDto.class);
        return new RespOrderDto().setCode(String.valueOf(res.code()))
                .setErrorMessage("errorType:"+respErrorDto.getType()+",msg:"+respErrorDto.getMessage());
    }


    /**
     * 构建物流订单数据传输对象
     * @param orderInfo
     * @return
     */
    private OrderCreateDto factoryOrder(TruckOrderDto orderInfo){

        PickupAndDeliveryDto pickupDto = factoryPickupAndDelivery(orderInfo.getShipperAddressDO());
        preOrderQuotationTimeCheck(pickupDto);
        PickupAndDeliveryDto deliveryDto = factoryPickupAndDelivery(orderInfo.getDeliveryAddressDO());
        preOrderQuotationTimeCheck(deliveryDto);
        PickupReadyDateDto pickupReadyDateDto = factoryPickupReadyDate(orderInfo);
        List<ShipperBoxDto> shipperBoxDtos = factoryBoxDtos(orderInfo);

        OrderCreateDto orderCreateDto = new OrderCreateDto();
        orderCreateDto.setDelivery(deliveryDto);
        orderCreateDto.setPickup(pickupDto);
        orderCreateDto.setFreight(shipperBoxDtos);
        orderCreateDto.setPickupReadyDate(pickupReadyDateDto);
        return orderCreateDto;
    }

    private void preOrderQuotationTimeCheck(PickupAndDeliveryDto addressDO) {
        if(StrUtil.isNotBlank(addressDO.getOpenTime()) && StrUtil.isNotBlank(addressDO.getCloseTime())) {
            return;
        }
        if(StrUtil.isBlank(addressDO.getOpenTime()) && StrUtil.isBlank(addressDO.getCloseTime())) {
            log.warn("订单信息中缺少发货时间窗口信息，设置默认值");
            addressDO.setOpenTime("0700");
            addressDO.setCloseTime("1900");
            return;
        }
        if(StrUtil.isBlank(addressDO.getOpenTime()) && StrUtil.isNotBlank(addressDO.getCloseTime())) {
            //设置窗口opentime在closeTime前3小时，但不超过 0100
            String closeTime = addressDO.getCloseTime();
            int closeHour = Integer.parseInt(closeTime.substring(0, 2));
            int openHour = Math.max(1, closeHour - 3); // Ensure it's at least 0100
            String openTime = String.format("%02d00", openHour);
            addressDO.setOpenTime(openTime);
            return;
        }
        //设置窗口closeTime在opentime后3小时，但不超过 2400
        String openTime = addressDO.getOpenTime();
        int openHour = Integer.parseInt(openTime.substring(0, 2));
        int closeHour = Math.min(24, openHour + 3); // Ensure it doesn't exceed 2400
        String closeTime = String.format("%02d00", closeHour);
        addressDO.setCloseTime(closeTime);
    }

    /**
     * 构建货物信息数据传输对象列表
     * @param orderInfo
     * @return
     */
    private List<ShipperBoxDto> factoryBoxDtos(TruckOrderDto orderInfo){
        List<TruckOrderBoxDO> orderBoxDOList = orderInfo.getOrderBoxDOList();
        if(CollUtil.isEmpty(orderBoxDOList)) {
            log.error("订单信息中缺少货物信息");
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "orderBoxDOList");
        }
        List<ShipperBoxDto> shipperBoxDtoList = new ArrayList<>();
        for (TruckOrderBoxDO truckOrderBoxDO : orderBoxDOList) {
            int weight = truckOrderBoxDO.getBoxWeight().intValueExact();
            int height = truckOrderBoxDO.getBoxHeight().intValueExact();
            int width = truckOrderBoxDO.getBoxWidth().intValueExact();
            int length = truckOrderBoxDO.getBoxLength().intValueExact();
            //todo: 单位换算
            ShipperBoxDto shipperBoxDto = new ShipperBoxDto(truckOrderBoxDO.getBoxUnit(),truckOrderBoxDO.getBoxQuantity(),
                    weight,length,width,height);
            if(StrUtil.isNotBlank(truckOrderBoxDO.getBoxDescription())) {
                shipperBoxDto.setDescription(truckOrderBoxDO.getBoxDescription());
            }
            shipperBoxDtoList.add(shipperBoxDto);
        }
        return shipperBoxDtoList;
    }

    /**
     * 构建发货准备就绪时间数据传输对象
     * @param orderInfo
     * @return
     */
    private PickupReadyDateDto factoryPickupReadyDate(TruckOrderDto orderInfo) {
        TruckOrderAddressDO shipperAddressDO = orderInfo.getShipperAddressDO();
        LocalDateTime pickReadyDatetime = shipperAddressDO.getPickReadyDatetime();
        if(pickReadyDatetime == null) {
            log.error("发货人地址信息中缺少发货准备就绪时间");
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COMMON_INFO_EXISTS, "pickReadyDatetime");
        }
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String datePart = pickReadyDatetime.format(dateFormatter);

        // 格式化为 HHmm (24小时制，不带冒号)
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmm");
        String timePart = pickReadyDatetime.format(timeFormatter);

        return new PickupReadyDateDto(datePart,timePart);
    }

    /**
     * 构建发货人和收货人及相关信息数据传输对象
     * @param addressDO
     * @return
     */
    private PickupAndDeliveryDto factoryPickupAndDelivery(TruckOrderAddressDO addressDO) {
        String accessorials = addressDO.getAccessorials();
        List<String> accessorialList = new ArrayList<>();
        if(StrUtil.isNotBlank(accessorials)){
            accessorialList = Arrays.asList(accessorials.split(","));
        }
        String oaEmail = addressDO.getOaEmail();
        List<String> emailList = new ArrayList<>();
        if(StrUtil.isNotBlank(oaEmail)){
            emailList = Arrays.asList(oaEmail.split(","));
        }
        String phoneNumber = addressDO.getOaTelphone();
        if(StrUtil.isBlank(addressDO.getOaTelphoneExtension())) {
            phoneNumber = phoneNumber+".e"+addressDO.getOaTelphoneExtension();
        }
        AddressDto addressDto = new AddressDto(addressDO.getOaStreetAddress1(), addressDO.getOaCity(), addressDO.getOaState(), addressDO.getOaPostcode());
        if(StrUtil.isNotBlank(addressDO.getOaStreetAddress2())) {
            addressDto.setSubStreet(addressDO.getOaStreetAddress2());
        }

        PickupAndDeliveryDto pickupAndDeliveryDto = new PickupAndDeliveryDto(addressDO.getOaCompany(),phoneNumber,addressDto,emailList,
                addressDO.getOpenTime(),addressDO.getCloseTime());
        if(CollUtil.isNotEmpty(accessorialList)) {
            pickupAndDeliveryDto.setAccessorials(accessorialList);
        }
        if(StrUtil.isNotBlank(addressDO.getReferenceNo())){
            pickupAndDeliveryDto.setReferenceNumber(addressDO.getReferenceNo());
        }
        if(StrUtil.isNotBlank(addressDO.getNote())) {
            pickupAndDeliveryDto.setNotes(addressDO.getNote());
        }
        if(StrUtil.isBlank(pickupAndDeliveryDto.getName())){
            pickupAndDeliveryDto.setName("unknow");
        }
        return pickupAndDeliveryDto;
    }
}
